<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>酒店管理系统登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent="onLogin">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" :loading="loading" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { login } from '../api/auth';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();
const form = ref({ username: '', password: '' });
const loading = ref(false);
const formRef = ref();

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const onLogin = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      const res = await login(form.value);
      console.log('登录响应:', res);
      if (res.token) {
        userStore.setToken(res.token);
        userStore.setUserInfo({
          username: res.username,
          role: res.role,
          userId: res.userId
        });
        console.log('保存的用户信息:', userStore.userInfo);
        ElMessage.success('登录成功');
        router.push('/');
      } else {
        ElMessage.error(res.message || '登录失败');
      }
    } catch (e) {
      ElMessage.error('登录失败，请检查用户名和密码');
    } finally {
      loading.value = false;
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #93a1df 0%, #4fa853 100%);
}
.login-card {
  width: 400px;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.login-card h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style> 